<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Controller;

use Admin\Controller\AdminActionController;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Sales\Entity\Order;
use Sales\Entity\OrderDeliveryAddress;
use Sales\Form\SearchOrderShipForm;

class ShipController extends AdminActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
    }

    /**
     * 订单发货单列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchOrderShipForm();
        $searchForm->get('express_state')->setValueOptions([1 => $this->translator->translate('已发货'), 2 => $this->translator->translate('未发货')]);
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOrderShipList($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['shipList' => $paginator, 'searchForm' => $searchForm];
    }

    /**
     * 发货单详情
     * @return array|\Laminas\Http\Response
     */
    public function detailAction()
    {
        $orderId    = (int) $this->params()->fromRoute('id', -1);
        $orderInfo  = $this->entityManager->getRepository(Order::class)->findOneBy(['orderId' => $orderId]);
        if ($orderInfo == null || ($orderInfo && $orderInfo->getDeliveryType() != 'delivery')) {
            return $this->redirect()->toRoute('sales-ship');
        }

        $queryData = $this->params()->fromQuery();

        $orderDeliveryInfo = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOneBy(['orderId' => $orderId]);
        if ($orderDeliveryInfo == null) return $this->redirect()->toRoute('sales-ship');

        return ['queryData' => $queryData, 'orderInfo' => $orderInfo, 'deliveryAddress' => $orderDeliveryInfo];
    }
}